/*
 * @Author: your name
 * @Date: 2021-03-23 13:55:18
 * @LastEditTime: 2021-03-23 13:56:03
 * @LastEditors: your name
 * @Description: In User Settings Edit
 * @FilePath: /xihaf-sign-tools/src/api/request.js
 */
class Request {
  constructor(host, path) {
    this.host = host;
    this.path = path;
  }

  request(url, method = "get", data = {}) {
    if (!url) {
      throw "not url";
    }

    return new Promise((resolve, reject) => {
      wx.request({
        url: `https://${this.host}${this.path}${url}`,
        data,
        header: { "content-type": "application/json" },
        method,
        dataType: "json",
        responseType: "text",
        success: result => {
          resolve(result.data);
        },
        fail: e => {
          reject(e);
        }
      });
    });
  }

  // 获取
  async get(url, data) {
    let { page = 1, pageSize = 20, fields = {}, srot = {} } = data;
    return await this.request(url, "GET", {
      limit: pageSize,
      skip: pageSize * (page - 1),
      fields,
      srot
    });
  }

  // 创建
  async post(url, data) {
    return await this.request(url, "POST", data);
  }

  // 替换
  async put(url, data) {
    return await this.request(url, "PUT", data);
  }

  // 删除
  async delete(url, data) {
    return await this.request(url, "DELETE", data);
  }

  // 更新
  async patch(url, data) {
    return await this.request(url, "PATCH", data);
  }
}

const singleton = (function() {
  let instance;

  return function(host, path) {
    if (!host || !path) {
      throw "not host || path";
    }

    if (!instance) {
      instance = new Request(host, path);
    }

    return instance;
  };
})();

module.exports = singleton;
